package com.reebake.ideal.security.authentication;

import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.security.entity.AccessTokenEntity;
import com.reebake.ideal.security.entity.SecurityPredictVO;
import com.reebake.ideal.security.handler.AuthenticationCaptchaHandler;
import com.reebake.ideal.security.properties.ServerSecurityProperties;
import com.reebake.ideal.security.util.JwtAuthUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class AuthenticationController {
    private final ServerSecurityProperties serverSecurityProperties;
    private final AuthenticationCaptchaHandler authenticationCaptchaHandler;

    @PostMapping("/auth/refresh")
    public String refreshToken(HttpServletRequest request, HttpServletResponse response) {
        AccessTokenEntity accessTokenEntity = JwtAuthUtil.refresh(serverSecurityProperties.getAccessTokenExpireIn());
        return accessTokenEntity.getAccessToken();
    }

    @PostMapping("/auth/predict")
    public SecurityPredictVO predict(@RequestBody SecurityPredictVO securityPredictVO) {
        SecurityPredictVO r = new SecurityPredictVO();
        String username = securityPredictVO.getUsername();
        if(StrUtil.isNotBlank(username)) {
            r.setRequireCaptcha(authenticationCaptchaHandler.requireCaptcha(username));
        }
        return r;
    }
}
